package com.minshenglife.zanzan.web.manage.filter;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.web.manage.cst.ManageKeys;


public class LoginFilter implements Filter {
	Logger log = LoggerFactory.getLogger(LoginFilter.class);
	
    
    /** 需要排除（不拦截）的URL的正则表达式 */
    private Pattern excepUrlPattern;
    
    /** 检查不通过时，转发的URL */
    private String forwardUrl;

    @Override
    public void init(FilterConfig cfg) throws ServletException {

        String excepUrlRegex = cfg.getInitParameter("excepUrlRegex");
        if (!StringUtils.isBlank(excepUrlRegex)) {
            excepUrlPattern = Pattern.compile(excepUrlRegex);
        }
        forwardUrl = cfg.getInitParameter("forwardUrl");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //该部分代码为后台管理代码 start
    	HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        log.debug("begin check user right!");
        String url=request.getRequestURI();
		log.debug("上送的url："+url);
        Object sessionObj = request.getSession(true).getAttribute(ManageKeys.SESSION_USER_KEY);

        log.debug("========"+sessionObj);
        String servletPath = request.getServletPath();
        String method = request.getMethod();

        // 如果请求的路径与forwardUrl相同，或请求的路径是排除的URL时，则直接放行
        if (servletPath.equals(forwardUrl) || excepUrlPattern.matcher(servletPath).matches()) {
            chain.doFilter(req, res);
            return;
        }
        // 如果Session为空，则跳转到指定页面
        if (sessionObj == null || !(method.equals("GET")||method.equals("POST"))) {
        	log.debug("======sesseion is null ,redirect");
            String contextPath = request.getContextPath();
            String redirect = servletPath + "?" + StringUtils.defaultString(request.getQueryString());
            response.sendRedirect(contextPath + StringUtils.defaultIfEmpty(forwardUrl, "/")
                            + "?redirect=" + URLEncoder.encode(redirect, "UTF-8"));
        } else {
        	log.debug("======session not is null,requeting");
            chain.doFilter(req, res);
        }
        //end
//    //start 该部分代码为对公网的代码，用于限制公网访问
//    	HttpServletResponse response=(HttpServletResponse)res;
//    	String errorPage=WXKeys.WX_BASEURL+"/jsp/error/error.html";
//    	response.sendRedirect(errorPage);
//		return;
//	//end
    }

    @Override
    public void destroy() {
    }
}


